from mcp.server.fastmcp import FastMCP, Context
import json

mcp = FastMCP(name="MCP Server")


@mcp.resource("data://message")
def static_message() -> str:
    return "这是一条来自于data://message的资源内容"


@mcp.tool()
async def long_running_task(task_name: str, ctx: Context, steps: int = 5) -> str:
    if ctx is None:
        return "未正确注入Context"
    await ctx.debug(f"开始执行任务:{task_name}")
    await ctx.debug(f"初始化任务环境")
    resource_result = await ctx.read_resource("data://message")
    resource_preview = ""
    for block in resource_result:
        resource_preview = getattr(block, "content", "<no-text>")
        break
    await ctx.info(f"读取资源成功:{resource_preview}")
    for i in range(steps):
        progress = (i + 1) / steps
        await ctx.report_progress(
            progress=progress * 100, total=100, message=f"Step {i+1}/{steps}"
        )
        await ctx.debug(f"Step {i+1}/{steps}")
    request_id = ctx.request_id
    await ctx.info(f"任务{task_name}成功完成,request_id={request_id}")
    return f"任务{task_name}完成，读到的资源内容为{resource_preview}"


if __name__ == "__main__":
    mcp.run(transport="stdio")
